function WordBook() {
	var lines = filesystem.readFile(preferences.tableName.value, true);
	var qlim = lines.length;
	var table = [];
	for (var i=0; i<qlim; i++)
		table[i] = lines[i].split("\t");
	var qnum = random(qlim);
	var qlist = [];
	var anums = [];
	var anames = [answer0, answer1, answer2];
	var answered = false;
	var fStat = system.widgetDataFolder + '/' + preferences.tableName.value;

	this.loadStatistics = function() {
		if (!filesystem.itemExists(fStat)) {
			for (var i=0; i<qlim; i++)
				qlist[i] = [0, 0, 0];
			return this;
		}
		var buf = filesystem.readFile(fStat, true);
		for (var i=0; i<qlim; i++)
			qlist[i] = buf[i].split("\t");
		return this;
	}
	this.loadStatistics();

	this.saveStatistics = function() {
		var buf = [];
		for (var i=0; i<qlim; i++)
			buf[i] = qlist[i][0] + "\t" + qlist[i][1] + "\t" + qlist[i][2];
		filesystem.writeFile(fStat, buf);
		return this;
	}
	
    this.nextQuestion = function() {
		qnum++;
		if (qnum >= lines.length)
			qnum = 0;
		
		question.data = table[qnum][1];
		anums[0] = qnum;
		anames[0].data = table[qnum][3];
		for (var i=1; i<anames.length; i++) {
			var dup;
			do {
				dup = false;
				anums[i] = random(qlim);
				for (var j=0; j<i; j++)
					if (anums[i] == anums[j]) {
						dup = true;
						break;
					}
			} while (dup);
		}
		for (var i=0; i<anames.length; i++) {
			var swap = random(anames.length);
			if (i == swap)
				continue;
			var tmp = anums[i];
			anums[i] = anums[swap];
			anums[swap] = tmp;
		}
		for (var i=0; i<anames.length; i++)
			anames[i].data = table[anums[i]][3];
		return this;
	}
	
	this.printStatistics = function() {
		var qes = 0;
		var ans = 0;
		var qcurr = 0;
		var acurr = 0;
		for (var i=0; i<qlim; i++) {
			qes += parseInt(qlist[i][0]);
			ans += parseInt(qlist[i][1]);
			if (qlist[i][2] != 0) {
				qcurr++;
				if (qlist[i][2] == 1)
					acurr++;
			}
		}
		statistics.data = 100 * acurr + '/' + 100 * ans;
		return this;
	}
	this.printStatistics();
	
	this.giveAnswer = function(num) {
		if (qnum == anums[num]) {
			qlist[qnum][0]++;
			if (!answered) {
				qlist[qnum][1]++;
				qlist[qnum][2] = 1;
			} else
				qlist[qnum][2] = -1;
			answered = false;
			this.printStatistics();
			this.nextQuestion();
			return this;
		}
		answered = true;
		anames[num].data = 'Wrong (間違い)';
		return this;
	}
	
}

function random(lim) {
	return Math.floor(Math.random() * lim);
}
